﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using GranitePackageSystem.GranitePackagingService;
using GranitePackageSystem.Views.ChildWindows;
using System.Collections.ObjectModel;

namespace GranitePackageSystem.Views.Request
{
    public partial class Licensing : Page
    {
        private bool inputsLock = false;
        private bool softwareContracted;
        private LicensingData licData;
        private GranitePackagingService.Request currentRequest = new GranitePackagingService.Request();
        private bool newLicensingData = true;
        private String originalLicKey;
        private ArrayOfString licKeyInfo;
        private int _errorCount = 0;
        private int _spawnedReqs = 0;
        public Licensing()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            checkRoles();            
            if (App.Current.Resources.Contains("Current Request"))
            {
                currentRequest = App.Current.Resources["Current Request"] as GranitePackagingService.Request;
                updateRequestNavTable();
                DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];

                if (currentRequest.PackageStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                {
                    boxPONumber.DataContext = new Models.PONumber();
                    busyIndicatorMain.IsBusy = true;
                    busyIndicatorMain.BusyContent = "Loading Request Licensing Data";

                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.getLicensingDataCompleted += new EventHandler<getLicensingDataCompletedEventArgs>(proxy_getLicensingDataCompleted_INIT);
                    proxy.getLicensingDataAsync(currentRequest);
                }
                else
                {
                    this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
                }
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
        }
        private void updateRequestNavTable()
        {
            DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
            if (App.Current.Resources.Contains("Current Request"))
            {
                expanderRequest.Visibility = System.Windows.Visibility.Visible;
                if (currentRequest.Stage.Equals("Staging"))
                {
                    linkTestingDetails.Visibility = System.Windows.Visibility.Visible;
                    if (currentRequest.VirtStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Visible;
                        if (currentRequest.PackageStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Visible;
                            if (currentRequest.LicensingStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                            }
                            else
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                            linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                else
                {
                    linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkTestingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }
       
        void proxy_getLicensingDataCompleted_INIT(object sender, getLicensingDataCompletedEventArgs e)
        {
            licData = e.Result;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getAllDivisionsCompleted += new EventHandler<getAllDivisionsCompletedEventArgs>(proxy_getAllDivisionsCompleted_INIT);
            proxy.getAllDivisionsAsync();
        }

        void proxy_getAllDivisionsCompleted_INIT(object sender, getAllDivisionsCompletedEventArgs e)
        {
            boxDivisonOfOwnership.ItemsSource = e.Result;
            if (e.Result.Count > 0)
            {
                boxDivisonOfOwnership.SelectedIndex = 0;
            }

            // If No existing Licensing Data
            if (licData.LicensingID == null)
            {
                panelLicenseEdit.Visibility = System.Windows.Visibility.Collapsed;
            }
            // Existing Licensing Data for Request
            else
            {
                panelLicenseEdit.Visibility = System.Windows.Visibility.Visible;
                newLicensingData = false;
                updateInputs(licData);
                lockInputs();
            }
            busyIndicatorMain.IsBusy = false;
        }

        private void updateInputs(LicensingData licData)
        {
            foreach (ComboBoxItem item in boxSoftwareOrigin.Items)
            {
                if(item.Content.Equals(licData.SoftwareOrigin))
                {
                    boxSoftwareOrigin.SelectedItem = item;
                    break;
                }
            }
            switch (licData.SoftwareOrigin)
            {
                case "Not General Mills Developed":
                    switch (licData.ProcurementMethod.ToUpper())
                    {
                        case "SAP SRM REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 0;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "MAXIMO REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 1;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "CORPORATE CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 2;                            
                            break;
                        case "PERSONAL CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 3;
                            break;
                        case "NO COST":
                            boxSoftwareProcurementMethod.SelectedIndex = 4;
                            panelSoftwareCost.Visibility = System.Windows.Visibility.Collapsed;
                            panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                            break;
                        case "IS Sourcing PCard":
                            break;
                        default:
                            break;
                    }

                    switch (licData.SoftwareCost)
                    {
                        case "0-$1,000":
                            boxSoftwareCost.SelectedIndex = 0;
                            break;
                        case "1,000-$10,000":
                            boxSoftwareCost.SelectedIndex = 1;
                            break;
                        case "$10,000+":
                            boxSoftwareCost.SelectedIndex = 2;
                            break;
                        default:
                            break;
                    }

                    softwareContracted = licData.SoftwareContracted;
                    updateSoftwareContracted(softwareContracted);

                    if (!licData.SoftwareContracted)
                    {
                        boxSoftwareEULA.SelectAll();
                        boxSoftwareEULA.Selection.Text = licData.SoftwareEULA;
                    }
                    if (licData.LicenseKeys.Count != 0)
                    {
                        if (licData.LicenseKeys.Count > 1)
                        {
                            boxLicenseKeyChoice.SelectedIndex = 1;
                        }
                        else
                        {
                            boxLicenseKeyChoice.SelectedIndex = 0;
                        }
                        foreach (LicenseKey licKey in licData.LicenseKeys)
                        {
                            listBoxLicenseKeys.Items.Add(licKey.Key.ToString());
                        }
                    }
                    else
                    {
                        boxLicenseKeyChoice.SelectedIndex = 2;
                    }
                    break;
                case "General Mills Developed":
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }

            foreach (Division division in boxDivisonOfOwnership.Items)
            {
                if (division.Name.Equals(licData.DivisionOfOwnership))
                {
                    boxDivisonOfOwnership.SelectedIndex = boxDivisonOfOwnership.Items.IndexOf(division);
                    break;
                }
            }
            if (!licData.DepartmentOfOwnership.Equals(string.Empty)) 
            {
                foreach (Department department in boxDepartmentOfOwnership.Items)
                {
                    if (department.name.Equals(licData.DepartmentOfOwnership))
                    {
                        boxDepartmentOfOwnership.SelectedIndex = boxDepartmentOfOwnership.Items.IndexOf(department);
                        break;
                    }
                }
            }
            else { panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed; }
            inputsLock = true;
        }

        private void lockInputs()
        {
            boxDepartmentOfOwnership.IsEnabled = false;
            boxDivisonOfOwnership.IsEnabled = false;
            boxLicenseKeyChoice.IsEnabled = false;
            boxPONumber.IsEnabled = false;
            boxSoftwareCost.IsEnabled = false;
            boxSoftwareEULA.IsEnabled = false;
            boxSoftwareOrigin.IsEnabled = false;
            boxSoftwareProcurementMethod.IsEnabled = false;
            listBoxLicenseKeys.IsEnabled = false;
            btnAddLicenseKey.IsEnabled = false;
            btnRemoveLicenseKey.IsEnabled = false;
            inputsLock = true;
            btnSaveLicensingData.IsEnabled = false;

            btnNext.Visibility = System.Windows.Visibility.Visible;
        }
        private void unlockInputes()
        {
            boxDepartmentOfOwnership.IsEnabled = true;
            boxDivisonOfOwnership.IsEnabled = true;
            boxLicenseKeyChoice.IsEnabled = true;
            boxPONumber.IsEnabled = true;
            boxSoftwareCost.IsEnabled = true;
            boxSoftwareEULA.IsEnabled = true;
            boxSoftwareOrigin.IsEnabled = true;
            boxSoftwareProcurementMethod.IsEnabled = true;
            listBoxLicenseKeys.IsEnabled = true;
            btnAddLicenseKey.IsEnabled = true;
            btnRemoveLicenseKey.IsEnabled = true;
            inputsLock = false;
            btnSaveLicensingData.IsEnabled = true;

            btnNext.Visibility = System.Windows.Visibility.Collapsed;

            DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
            currentRequest.LicensingStepComplete = MIN_SQL_DATE;
            updateRequestNavTable();
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Saving Request";

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_Lock_Unlock);
            proxy.saveRequestAsync(currentRequest);
        }

        void proxy_saveRequestCompleted_Lock_Unlock(object sender, saveRequestCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
        }

        private void btnSoftwareContracted_YES_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!inputsLock) { updateSoftwareContracted(true); }
        }

        private void btnSoftwareContracted_NO_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!inputsLock) { updateSoftwareContracted(false); }
        }

        private void updateSoftwareContracted(bool status)
        {
            softwareContracted = status;
            if (status == true)
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                btnSoftwareContracted_NO.Background = new SolidColorBrush();
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush();
                btnSoftwareContracted_NO.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void boxSoftwareOrigin_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (boxSoftwareOrigin.SelectedIndex == 1)
                {
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch { }
        }

        private void boxLicenseKeyChoice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (boxLicenseKeyChoice.SelectedIndex == 2)
                {
                    panelLicenseKeyUploader.Visibility = System.Windows.Visibility.Collapsed;
                    listBoxLicenseKeys.Items.Clear();
                    licData.LicenseKeys.Clear();
                }
                else
                {
                    panelLicenseKeyUploader.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch { }
        }

        private void boxSoftwareProcurementMethod_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                switch (boxSoftwareProcurementMethod.SelectedIndex)
                {
                    case 0:
                        panelPONumber.Visibility = System.Windows.Visibility.Visible;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 1:
                        panelPONumber.Visibility = System.Windows.Visibility.Visible;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 2:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 3:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 4:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Collapsed;
                        break;
                    default:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                }
            }
            catch { }
        }

        private void boxDivisonOfOwnership_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (((Division)boxDivisonOfOwnership.SelectedItem).Departments.Count > 0)
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Visible;
                    boxDepartmentOfOwnership.SelectedIndex = 0;
                }
                else
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch { }
        }

        private void btnAddLicenseKey_Click(object sender, RoutedEventArgs e)
        {
            LicenseKeyEntry licKeyEntryWindow = new LicenseKeyEntry();
            licKeyEntryWindow.Closed += new EventHandler(licKeyEntryWindow_Closed);
            licKeyEntryWindow.Show();
        }

        void licKeyEntryWindow_Closed(object sender, EventArgs e)
        {
            if (((LicenseKeyEntry)sender).DialogResult == true && !((LicenseKeyEntry)sender).boxLicenseKey.Text.Equals(String.Empty))
            {
                listBoxLicenseKeys.Items.Add(((LicenseKeyEntry)sender).boxLicenseKey.Text);

                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Searching environmnet for additional Keys - Looking for Root Key";
                originalLicKey = ((LicenseKeyEntry)sender).boxLicenseKey.Text;

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 15, 0);
                proxy.getRequestVirtualMachineCompleted += new EventHandler<getRequestVirtualMachineCompletedEventArgs>(proxy_getRequestVirtualMachineCompleted);
                proxy.getRequestVirtualMachineAsync(currentRequest);
            }
        }

        void proxy_getRequestVirtualMachineCompleted(object sender, getRequestVirtualMachineCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = TimeSpan.FromMinutes(60);
            if (e.Result != null)
            {
                proxy.getLicKeyRegistryKeyCompleted += new EventHandler<getLicKeyRegistryKeyCompletedEventArgs>(proxy_getLicKeyRegistryKeyCompleted);
                proxy.getLicKeyRegistryKeyAsync(originalLicKey, e.Result.Name);
            }
        }

        void proxy_getLicKeyRegistryKeyCompleted(object sender, getLicKeyRegistryKeyCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = TimeSpan.FromMinutes(60);

            licKeyInfo = e.Result;

            if (licKeyInfo[0] != null && licKeyInfo[0] != string.Empty)
            {
                busyIndicatorMain.BusyContent = "Searching environmnet for additional Keys - Looking for Install Base";
                proxy.getPackageListCompleted += new EventHandler<getPackageListCompletedEventArgs>(proxy_getPackageListCompleted);
                proxy.getPackageListAsync(currentRequest);
            }
            else { busyIndicatorMain.IsBusy = false; MessageBox.Show("Could not find additional keys"); }
        }

        void proxy_getPackageListCompleted(object sender, getPackageListCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
            proxy.getApplicationInstallBaseInformationCompleted += new EventHandler<getApplicationInstallBaseInformationCompletedEventArgs>(proxy_getApplicationInstallBaseInformationCompleted);
            proxy.getApplicationInstallBaseInformationAsync(e.Result[0].Name, e.Result[0].Version);
        }

        void proxy_getApplicationInstallBaseInformationCompleted(object sender, getApplicationInstallBaseInformationCompletedEventArgs e)
        {
            ObservableCollection<ApplicationInformation> resultList = e.Result;
            
            if (e.Result.Count > 0)
            {
                busyIndicatorMain.BusyContent = "Searching environmnet for additional Keys - Searching Remote Machines";
                _spawnedReqs = resultList.Count;
                foreach (ApplicationInformation appInfo in resultList)
                {
                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
                    proxy.getLicenseKeyCompleted += new EventHandler<getLicenseKeyCompletedEventArgs>(proxy_getLicenseKeyCompleted);
                    proxy.getLicenseKeyAsync(licKeyInfo[0], licKeyInfo[1], appInfo.installationComputer);
                }
            }
            else { MessageBox.Show("Did not find an install base"); busyIndicatorMain.IsBusy = false; }
        }

        void proxy_getLicenseKeyCompleted(object sender, getLicenseKeyCompletedEventArgs e)
        {
            _spawnedReqs--;

            listBoxLicenseKeys.Items.Add(e.Result);

            if (_spawnedReqs == 0)
            {
                busyIndicatorMain.IsBusy = false;
            }
        }

        private void btnRemoveLicenseKey_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxLicenseKeys.SelectedItem != null)
            {
                listBoxLicenseKeys.Items.Remove(listBoxLicenseKeys.SelectedItem);
            }
        }

        private void btnEditLicensingData_Click(object sender, RoutedEventArgs e)
        {
            panelLicenseEdit.Visibility = System.Windows.Visibility.Collapsed;
            unlockInputes();
        }

        private void checkRoles()
        {
            Web.User user = WebContext.Current.User;
            bool userInARole = false;

            if (user.IsInRole("GENMILLS\\GPS_Requesters")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_Administrators")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_LicensingApprovers")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_DeploymentApprovers")) { userInARole = true; }

            if (userInARole) { }
            else { this.NavigationService.Navigate(new System.Uri("/Unauthorized", System.UriKind.Relative)); }
        }

        private bool validateInputFields()
        {
            licData.SoftwareOrigin = boxSoftwareOrigin.SelectionBoxItem.ToString();
            licData.RequestID = currentRequest.requestID;
            switch (licData.SoftwareOrigin)
            {
                case "Not General Mills Developed":
                    licData.ProcurementMethod = boxSoftwareProcurementMethod.SelectionBoxItem.ToString();

                    switch (licData.ProcurementMethod)
                    {
                        case "SAP SRM request":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            if (boxPONumber.Text.Equals(string.Empty))
                            {
                                MessageBox.Show("Must Enter a PO Number");
                                return false;
                            }
                            else
                            {
                                licData.PO_Number = boxPONumber.Text;
                            }
                            break;
                        case "Maximo Request":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            if (boxPONumber.Text.Equals(string.Empty))
                            {
                                MessageBox.Show("Must Enter a PO Number");
                                return false;
                            }
                            else
                            {
                                licData.PO_Number = boxPONumber.Text;
                            }
                            break;
                        case "Corporate Credit Card":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            break;
                        case "Personal Credit Card":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            break;
                        case "No Cost":
                            break;
                        default:
                            MessageBox.Show("Invalid Procurement Method");
                            return false;
                    }

                    licData.SoftwareContracted = softwareContracted;

                    if (!licData.SoftwareContracted)
                    {
                        boxSoftwareEULA.SelectAll();
                       
                        if (boxSoftwareEULA.Selection.Text.ToString().Equals(string.Empty))
                        {
                            MessageBox.Show("For non contracted software you must enter the EULA");
                            return false;
                        }
                        else
                        {
                            licData.SoftwareEULA = boxSoftwareEULA.Selection.Text.ToString();
                        }
                    }

                    if (boxLicenseKeyChoice.SelectedIndex != 2)
                    {
                        if (listBoxLicenseKeys.Items.Count > 0)
                        {
                            licData.LicenseKeys = new System.Collections.ObjectModel.ObservableCollection<LicenseKey>();
                            foreach (String licKey in listBoxLicenseKeys.Items)
                            {
                                licData.LicenseKeys.Add(new LicenseKey() { Key = licKey, LicenseID = licData.LicensingID, LicenseKeyID = System.Guid.NewGuid().ToString() });
                            }
                        }
                        else
                        {
                            MessageBox.Show("You must enter software license keys");
                            return false;
                        }
                    }
                    break;
                case "General Mills Developed":
                    break;
                default:
                    MessageBox.Show("Invalid Software Origin");
                    return false;
            }

            licData.DivisionOfOwnership = ((Division)boxDivisonOfOwnership.SelectedItem).Name.ToString();

            if(panelDepartmentOfOwnership.Visibility == System.Windows.Visibility.Visible)
            {
                licData.DepartmentOfOwnership = ((Department)boxDepartmentOfOwnership.SelectedItem).name.ToString();
            }

            return true;
        }

        private void btnSaveLicensingData_Click(object sender, RoutedEventArgs e)
        {
            if (validateInputFields())
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Licensing Data";

                if (newLicensingData)
                {
                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.createLicensingDataCompleted += new EventHandler<createLicensingDataCompletedEventArgs>(proxy_createLicensingDataCompleted);
                    proxy.createLicensingDataAsync(licData);
                }
                else
                {
                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.saveLicensingDataCompleted += new EventHandler<saveLicensingDataCompletedEventArgs>(proxy_saveLicensingDataCompleted);
                    proxy.saveLicensingDataAsync(licData);
                }
            }
        }

        void proxy_saveLicensingDataCompleted(object sender, saveLicensingDataCompletedEventArgs e)
        {
            currentRequest.LicensingStepComplete = DateTime.UtcNow;

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
            proxy.saveRequestAsync(currentRequest);   
        }

        void proxy_saveRequestCompleted(object sender, saveRequestCompletedEventArgs e)
        {
            panelLicenseEdit.Visibility = System.Windows.Visibility.Visible;
            lockInputs();

            updateRequestNavTable();

            busyIndicatorMain.IsBusy = false;
            this.NavigationService.Navigate(new Uri("/Request/RequestSummary", UriKind.Relative));
        }

        void proxy_createLicensingDataCompleted(object sender, createLicensingDataCompletedEventArgs e)
        {
            currentRequest.LicensingStepComplete = DateTime.UtcNow;

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
            proxy.saveRequestAsync(currentRequest);
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Saving Request";
            currentRequest.LicensingStepComplete = DateTime.UtcNow;

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_EXIT);
            proxy.saveRequestAsync(currentRequest);
        }

        void proxy_saveRequestCompleted_EXIT(object sender, saveRequestCompletedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Request/RequestSummary", UriKind.Relative));
        }

        private void boxPONumber_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxRequestOrigin_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (boxRequestOrigin != null)
            {
                currentRequest.IncomingSource = ((ComboBoxItem)boxRequestOrigin.SelectedItem).Content.ToString();
                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);
            }
        }
    }
}
